/*
 * nodelist.cpp
 *
 *  Created on: 15/11/2012
 *      Author: cvan680
 */


#include "nodelist.h"
#include <algorithm>

namespace voreen {

NodeList::NodeList(){}

NodeList::NodeList(string set){
	// FIXME unpack set into nodes
	nodes_ = vector<Node>();
	tmap_ = TechniqueMap();
	unpack(set);
}

Node NodeList::get(int index){
	if(index < 0 || index >= nodes_.size()){ return Node(tmap_.getNULL()); }
	return nodes_.at(index);
}

int NodeList::length(){
	return nodes_.size();
}

void NodeList::replaceFirstOccurrence(NodeList pre, NodeList post){
	// FIXME test
	if(!contains(pre)){ return; }
	int fIn = indexOf(pre);
	int nSize = this->length() + post.length() - pre.length();
	vector<Node> newN = vector<Node>();
	for(int i=0; i<fIn; ++i){ newN.push_back(this->get(i)); }
	for(int j=0; j<post.length(); ++j){ newN.push_back(post.get(j)); }
	for(int k=fIn+pre.length(); k<this->length(); ++k){ newN.push_back(this->get(k)); }
	nodes_ = newN;
}

int NodeList::indexOf(NodeList set){
	// FIXME test
	int l = set.length();
	bool tempTest;
	for(int i=0; i+l<=this->length(); ++i){
		tempTest = true;
		for(int j=0; j<l; ++j){
			if(!this->get(i+j).equals(set.get(j))){
				tempTest = false;
				break;
			}
		}
		if(tempTest){ return i; }
	}
	return -1;
}

bool NodeList::contains(NodeList set){
	// FIXME test
	return indexOf(set) >= 0;
}

void NodeList::unpack(string set){

	nodes_.clear();

	TechniqueWrapper twrapper;
	Node tnode;
	bool nothing_found;
	while(set.length() > 0){
		int i=0;
		nothing_found = true;
		while(nothing_found && i < set.length()){
			i++;
			twrapper = tmap_.get(set.substr(0, i));
			if(twrapper.uniqueID_!=-1){ // NOT FOUND identifier
				nothing_found = false;
				tnode = Node(twrapper);
				nodes_.push_back( tnode );
			}
		}
		set.erase(0, i); //remove from string
	}
}

void NodeList::printMe(){
	std::cout << "{";
	for(int i=0; i<this->length(); ++i){
		std::cout << "[" << this->get(i).getIdentifier() << "]";
	}
	std::cout << "}";
}

}
